package com.gastudio.Protocol;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.charset.Charset;

/**
 * 编码器【把对象转换成字节流】
 * Created by 余艾龙 on 2017/6/21.
 */
public class ProtocolEncoder extends ProtocolEncoderAdapter {
    private final Charset charset;//定义数据包的编码集

    public ProtocolEncoder(Charset charset) {
        this.charset = charset;
    }
    //将java对象object，转换成二进制流,并发送
    @Override
    public void encode(IoSession session, Object object, ProtocolEncoderOutput output) throws Exception {
        ProtocolPack value=(ProtocolPack)object;
        IoBuffer buf=IoBuffer.allocate(value.getLength());//设置缓冲区空间大小
        buf.setAutoExpand(true);//设置缓冲区自动增长
        buf.putInt(value.getLength());//设置报头和报文的组合大小
        buf.put(value.getFlag());//设置报文字节数
        if(value.getContent()!=null){
            buf.put(value.getContent().getBytes());
        }
        buf.flip();
        output.write(buf);
    }
}
